2. ODBC
There is nothing
earth-shattering or truly groundbreaking here, but let's walk though an
example to see how ODBC connections work and illustrate that your ODBC
classes still work as you're used to. Follow these steps:
Do this the proper way and create an enumeration to handle the type of connection you're using.
Modify the GetConString
method as shown in the following snippet to take a parameter. The
parameter lets you specify the connection type so you can return the
correct type of connection string (either ADO.NET or ODBC). Be sure to
use your correct password and server name with the correct server. If
the value of ADO_NET is passed into this method, the ADO.NET connection string is returned; otherwise the ODBC connection string is returned:
enum ConnType
{
ADO_NET = 1,
ODBC = 2
}
string GetConString(ConnType connType)
{
if (connType == ConnType.ADO_NET)
return "Server=tcp:servername.database.windows.net;Database=TechBio;
User ID=SQLScott@servername;Password=password;
Trusted_Connection=False;Encrypt=True;";
else
return "Driver={SQL Server Native Client 10.0};Server=tcp:servername.database.windows.net;
Database=TechBio;Uid=SQLScott@servername;Pwd=password;Encrypt=yes;";
}
Place
a second button on the form, along with a DataGridView. In its click
event, add the following code. This code is just like the code from the
ADO.NET example, but it uses the Odbc data classes versus the Sql
data classes. For clarity, change the Text property of this new button
to "ODBC" so you know the difference between this button and the first
button. Notice in the code that the value "ODBC" is passed in the GetConString method, returning the ODBC connection string:
string connStr = GetConString(ConnType.ODBC);
using (OdbcConnection conn = new OdbcConnection(connStr))
{
try
{
conn.Open();
OdbcDataAdapter da = new OdbcDataAdapter();
OdbcCommand cmd = new OdbcCommand("SELECT Name FROM Users", conn);
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
DataSet ds = new DataSet("Users");
da.Fill(ds);
listBox1.DataSource = ds.Tables[0];
dataGridView1.DataSource = ds.Tables[0];
listBox1.DisplayMember = "Name";
}
catch (OdbcException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
Run
the project, and click the ODBC button. As in the previous example, the
list box populates with the names from the Users table. The grid also
populates with the same set of names (see Figure 2).
From these examples, you can
see that connecting to and querying SQL Azure is no different from
connecting to a local instance of SQL Server.
So far we have discussed
connecting with ADO.NET and ODBC along with the different options we
have with each, so let's continue the discussion and talk about using
the SqlCmd utility.